import React, { useState, useEffect, useCallback } from 'react';
import { useHistory } from 'react-router-dom';
import { Radio, Spin } from 'antd';
import { ArrowUpOutlined, ArrowDownOutlined, RightOutlined } from '@ant-design/icons';
import { flatTryCatch } from '../../../../servers/http';
import { timeOptions, timeMap } from '../constant';
import type { ITimeSpan } from '../constant';
import './OneOfThree.scss';

interface Props {
  fetchApi: (timeSpan: string) => Promise<any>;
  title: string;
  path: string;
}

const arrow = {
  increase: <ArrowUpOutlined />,
  decrease: <ArrowDownOutlined />,
};

const OneOfThree: React.FC<Props> = ({ fetchApi, title, path }) => {
  const history = useHistory();
  const [timeSpan, setTimeSpan] = useState<ITimeSpan>(timeOptions[0].value);
  const [statisticData, setStatisticData] = useState<any>({});
  const [loading, setLoading] = useState(false);

  const fetchData = useCallback(async () => {
    setLoading(true);
    const { response, error } = await flatTryCatch(fetchApi(timeSpan));
    setLoading(false);
    if (error) return;
    setStatisticData(response.data);
  }, [fetchApi, timeSpan]);

  // 初始化加载和timeSpan变化时加载数据
  useEffect(() => {
    fetchData();
  }, [fetchData, timeSpan]);

  // 处理时间范围变化
  const handleTimeSpanChange = (e: any) => {
    setTimeSpan(e.target.value);
  };

  return (
    <div className="single-item">
      <Spin spinning={loading}>
        <div className="metric-title">
          <div className="title-txt">{title}</div>
          <Radio.Group
            value={timeSpan}
            onChange={handleTimeSpanChange}
            buttonStyle="solid"
            optionType="button"
            options={timeOptions}
            size="small"
          />
        </div>
        <div className="metric-main">
          <div className="metric-value">{statisticData.sendSuccess ?? 0}</div>
          <div className="metric-comparison">
            <span>同比上{timeMap[timeSpan]}</span>
            <div className={`comparison-icon ${statisticData.monthOnMonth}`}>
              {arrow[statisticData.monthOnMonth]}
            </div>
            <span>{statisticData.monthOnMonthPercentage}%</span>
          </div>
        </div>
        <div className="metric-rate">
          {path.includes('intelligentCall') ? '呼叫' : '发送'}成功率 {statisticData.sendSuccessRate}
          %
        </div>
        <div className="metric-bottom">
          <div className="metric-cost">
            {statisticData.chargeSmsCount != null && `发送量计费${statisticData.chargeSmsCount}条 `}
            费用 {statisticData.cost}元
          </div>
          <RightOutlined onClick={() => history.push(path)} />
        </div>
      </Spin>
    </div>
  );
};

export default OneOfThree;
